package com.online.study.content.service.impl;

import cn.hutool.core.util.StrUtil;
import com.online.study.content.entity.CourseBase;
import com.online.study.content.model.dto.CourseBaseDto;
import com.online.study.content.model.dto.QueryCourseParamsDto;
import com.online.study.content.repository.CourseBaseRepository;
import com.online.study.content.service.CourseBaseService;
import com.online.study.content.service.mapstruct.CourseBaseMapper;
import com.online.study.model.Page;
import com.online.study.model.PageParams;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseBaseServiceImpl implements CourseBaseService {

    @Resource
    private CourseBaseRepository courseBaseRepository;

    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Override
    public Page<CourseBaseDto> queryCourseBaseList(PageParams params, QueryCourseParamsDto queryCourseParamsDto) {
        Page<CourseBaseDto> page = new Page<>();
        Pageable of = PageRequest.of(params.getPageNo() - 1, params.getPageSize());
        org.springframework.data.domain.Page<CourseBase> all = courseBaseRepository.findAll(((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StrUtil.isNotBlank(queryCourseParamsDto.getCourseName())) {
                Predicate predicate = criteriaBuilder.like(root.get("name").as(String.class), "%" + queryCourseParamsDto.getCourseName() + "%");
                predicates.add(predicate);
            }
            if (StrUtil.isNotBlank(queryCourseParamsDto.getAuditStatus())) {
                Predicate predicate = criteriaBuilder.equal(root.get("auditStatus").as(String.class), queryCourseParamsDto.getAuditStatus());
                predicates.add(predicate);
            }
            if (StrUtil.isNotBlank(queryCourseParamsDto.getPublishStatus())) {
                Predicate predicate = criteriaBuilder.equal(root.get("status").as(String.class), queryCourseParamsDto.getPublishStatus());
                predicates.add(predicate);
            }
            return query.where(predicates.toArray(new Predicate[0])).getRestriction();
        }), of);
        page.setPage(params.getPageNo());
        page.setPageSize(params.getPageSize());
        page.setCounts(all.getTotalElements());
        page.setItems(courseBaseMapper.toDto(all.getContent()));
        return page;
    }
}
